package com.jarveis.frame.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.jarveis.frame.io.HttpUtil;
import com.jarveis.frame.lang.CharacterUtil;
import com.jarveis.frame.security.MD5Cipher;

/**
 * 数据访问工具类
 * 
 * @author liuguojun
 */
public class DBS4ServletClient {

	private static final Logger logger = Logger
			.getLogger(DBS4ServletClient.class);

	public static final String ERR_CODE = "@errcode";
	public static final String ERR_DESC = "@errdesc";

	private static Map configMap = new HashMap();

	/**
	 * 添加配置
	 * 
	 * @param agent
	 * @param link
	 * @param md5Key
	 */
	public static void addConfig(int agent, String link) {
		addConfig(agent, link, CharacterUtil.UTF8);
	}

	/**
	 * 添加配置
	 * 
	 * @param agent
	 * @param link
	 * @param encoding
	 * @param md5Key
	 */
	public static void addConfig(int agent, String link, String encoding) {
		configMap.put(agent, new String[] { link, encoding });
	}

	/**
	 * 访问接口
	 * 
	 * @param in
	 * @return
	 */
	public static Param callInterface(Param in) throws Exception {
		int agent = in.getHead().getInteger("@agent");

		String[] config = (String[]) configMap.get(agent);

		return callPlain(config[0], config[1], in.toString());
	}

	/**
	 * 明文访问接口
	 * 
	 * @param link
	 * @param encoding
	 * @param inStr
	 * @return
	 */
	private static Param callPlain(String link, String encoding, String inStr)
			throws Exception {
		Param out = null;

		HttpUtil httpUtil = new HttpUtil(link, HttpUtil.HttpMethod.POST,
				encoding);
		httpUtil.addParam("_message", inStr);
		if (httpUtil.doRequest()) {
			byte[] resultArr = httpUtil.getRespData();
			out = new Param(new String(resultArr));
		} else {
			out = new Param("Resp");
		}

		return out;
	}
}
